/*
 * @Author: FanWeiHua
 * @Date: 2021-07-23 11:54:17
 * @LastEditTime: 2021-07-23 17:47:18
 * @Description: 日志服务
 */
import Logan from 'logan-web';
// import { getItemFromDB } from 'idb-managed';
const timeFormat2Day = date => {
  var Y = date.getFullYear();
  var M = date.getMonth() + 1;
  var D = date.getDate();
  return Y + '-' + (M < 10 ? '0' + M : M) + '-' + (D < 10 ? '0' + D : D);
};
/**
 * 初始化
 */
Logan.initConfig({
  dbName: 'log_web_db',
  succHandler: logItem => {
    console.log(logItem);
    console.log(JSON.parse(logItem.logContent));
  }
});
setTimeout(() => {
  var logType = 1;
  var content = 'testCustomLog';
  Logan.customLog({
    logContent: JSON.stringify({
      t: logType,
      c: encodeURIComponent(content),
      d: Date.now().toString()
    }),
    encryptVersion: 2
  });
  // setTimeout(async () => {
  //   const studentInfo = await getItemFromDB('log_web_db', 'logan_detail_table', 1);
  //   console.log(studentInfo.logString);
  // }, 2000);
  var now = new Date();
  var sevenDaysAgo = new Date(+now - 1 * 24 * 3600 * 1000);
  const reportResult = Logan.report({
    xhrOptsFormatter: (logItemStrings, logPageNo, logDayString) => {
      const formData = new FormData();
      formData.append('fileDate', logDayString);
      formData.append('logArray', logItemStrings.toString());
      formData.append('logPageNo', logPageNo);
      formData.append('webSource', 'browser');
      formData.append('fromDayString', timeFormat2Day(sevenDaysAgo));
      formData.append('toDayString', timeFormat2Day(now));
      formData.append('environment', navigator.userAgent);
      return {
        reportUrl: 'http://10.0.3.184:8000/putLog',
        data: formData,
        withCredentials: false,
        responseDealer: function (xhrResponseText) {
          if (xhrResponseText === 'well done') {
            return {
              resultMsg: 'Report succ'
            };
          } else {
            return {
              resultMsg: 'Report fail',
              desc: 'what is wrong with this report'
            };
          }
        }
      };
    }
  });
  reportResult.then(result => {
    console.log(result);
  });
}, 4000);
window.addEventListener('error', e => {
  // console.log(e);
  // console.log(e.message);
  // console.log(e.lineno);
  // console.log(e.colno);
  // console.log(e.filename);
  // console.log(e.error);
  // console.log(new Date().getTime());
  // var time = new Date(new Date().getTime());
  // var y = time.getFullYear(); // getFullYear方法以四位数字返回年份
  // var M = time.getMonth() + 1; // getMonth方法从 Date 对象返回月份 (0 ~ 11)，返回结果需要手动加一
  // var d = time.getDate(); // getDate方法从 Date 对象返回一个月中的某一天 (1 ~ 31)
  // var h = time.getHours(); // getHours方法返回 Date 对象的小时 (0 ~ 23)
  // var m = time.getMinutes(); // getMinutes方法返回 Date 对象的分钟 (0 ~ 59)
  // var s = time.getSeconds(); // getSeconds方法返回 Date 对象的秒数 (0 ~ 59)
  // console.log(y + '-' + M + '-' + d + ' ' + h + ':' + m + ':' + s);
});
